#!/bin/bash

# SpringBoot启动问题诊断脚本
# 版本: 1.0.0
# 专门用于诊断SpringBoot应用启动失败问题

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 计数器
error_count=0
fix_count=0

# 创建日志文件
log_dir="logs"
log_file="${log_dir}/startup-diagnostics-$(date +%Y%m%d-%H%M%S).log"
mkdir -p "$log_dir"

echo "========================================" | tee "$log_file"
echo "     SpringBoot启动问题诊断脚本         " | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "版本: 1.0.0" | tee -a "$log_file"
echo "专门用于诊断SpringBoot应用启动失败问题" | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "" | tee -a "$log_file"

echo "[$(date)] 开始启动问题诊断" >> "$log_file"

echo "[1/6] 分析应用启动日志..." | tee -a "$log_file"

# 查找最新的启动日志
startup_log=""
if [ -f "backend/logs/employment.log" ]; then
    startup_log="backend/logs/employment.log"
elif [ -f "backend/logs/employment-dev.log" ]; then
    startup_log="backend/logs/employment-dev.log"
elif [ -f "logs/employment.log" ]; then
    startup_log="logs/employment.log"
fi

if [ -n "$startup_log" ]; then
    echo -e "${GREEN}✅ 找到启动日志文件: $startup_log${NC}" | tee -a "$log_file"
    
    echo "    正在分析错误信息..."
    
    # 检查常见错误模式
    if grep -i -E "(Exception|Error|Failed|Cannot|Unable)" "$startup_log" > temp_errors.txt 2>/dev/null && [ -s temp_errors.txt ]; then
        ((error_count++))
        echo -e "${RED}    ❌ 发现以下错误信息:${NC}" | tee -a "$log_file"
        echo "[ERROR] 发现启动错误" >> "$log_file"
        cat temp_errors.txt | tee -a "$log_file"
        rm temp_errors.txt
    else
        echo -e "${GREEN}    ✅ 未发现明显错误信息${NC}" | tee -a "$log_file"
        [ -f temp_errors.txt ] && rm temp_errors.txt
    fi
else
    echo -e "${YELLOW}⚠️  未找到启动日志文件${NC}" | tee -a "$log_file"
    echo "[WARN] 未找到启动日志文件" >> "$log_file"
fi

echo "" | tee -a "$log_file"
echo "[2/6] 检查依赖冲突..." | tee -a "$log_file"

if cd backend 2>/dev/null; then
    echo "    正在分析Maven依赖树..."
    if mvn dependency:tree > ../temp_dependency_tree.txt 2>&1; then
        echo -e "${GREEN}✅ Maven依赖树生成成功${NC}" | tee -a "../$log_file"
        
        # 检查常见的依赖冲突
        if grep -i -E "(conflict|duplicate|version)" ../temp_dependency_tree.txt > ../temp_conflicts.txt 2>/dev/null && [ -s ../temp_conflicts.txt ]; then
            ((error_count++))
            echo -e "${RED}    ❌ 检测到可能的依赖冲突:${NC}" | tee -a "../$log_file"
            echo "[ERROR] 检测到依赖冲突" >> "../$log_file"
            cat ../temp_conflicts.txt | tee -a "../$log_file"
            rm ../temp_conflicts.txt
        else
            echo -e "${GREEN}    ✅ 未发现明显的依赖冲突${NC}" | tee -a "../$log_file"
            [ -f ../temp_conflicts.txt ] && rm ../temp_conflicts.txt
        fi
        rm ../temp_dependency_tree.txt
    else
        echo -e "${RED}❌ Maven依赖分析失败${NC}" | tee -a "../$log_file"
        echo "[ERROR] Maven依赖分析失败" >> "../$log_file"
        ((error_count++))
    fi
    cd ..
else
    echo -e "${RED}❌ 无法进入backend目录${NC}" | tee -a "$log_file"
    echo "[ERROR] 无法进入backend目录" >> "$log_file"
    ((error_count++))
fi

echo "" | tee -a "$log_file"
echo "[3/6] 验证配置文件..." | tee -a "$log_file"

# 检查主配置文件
if [ -f "backend/src/main/resources/application.yml" ]; then
    echo -e "${GREEN}✅ application.yml 存在${NC}" | tee -a "$log_file"
    
    # 简单的YAML语法检查
    if python3 -c "import yaml; yaml.safe_load(open('backend/src/main/resources/application.yml'))" 2>/dev/null; then
        echo -e "${GREEN}    ✅ YAML语法验证通过${NC}" | tee -a "$log_file"
    else
        echo -e "${YELLOW}    ⚠️  YAML语法可能存在问题${NC}" | tee -a "$log_file"
        echo "[WARN] YAML语法可能存在问题" >> "$log_file"
    fi
else
    echo -e "${RED}❌ application.yml 不存在${NC}" | tee -a "$log_file"
    echo "[ERROR] application.yml 不存在" >> "$log_file"
    ((error_count++))
fi

# 检查开发环境配置文件
if [ -f "backend/src/main/resources/application-dev.yml" ]; then
    echo -e "${GREEN}✅ application-dev.yml 存在${NC}" | tee -a "$log_file"
else
    echo -e "${YELLOW}⚠️  application-dev.yml 不存在，使用默认配置${NC}" | tee -a "$log_file"
    echo "[WARN] application-dev.yml 不存在" >> "$log_file"
fi

echo "" | tee -a "$log_file"
echo "[4/6] 检查数据库连接..." | tee -a "$log_file"

# 从配置文件中提取数据库信息（简化版本）
db_host="localhost"
db_port="3306"
db_user="root"
db_password="123456"

echo "    尝试连接数据库 $db_host:$db_port..."
if command -v mysql >/dev/null 2>&1; then
    if mysql -h "$db_host" -P "$db_port" -u "$db_user" -p"$db_password" -e "SELECT 1;" >/dev/null 2>&1; then
        echo -e "${GREEN}✅ 数据库连接成功${NC}" | tee -a "$log_file"
        
        # 检查数据库是否存在
        if mysql -h "$db_host" -P "$db_port" -u "$db_user" -p"$db_password" -e "USE employment_db; SELECT 1;" >/dev/null 2>&1; then
            echo -e "${GREEN}    ✅ employment_db 数据库已存在${NC}" | tee -a "$log_file"
        else
            echo -e "${RED}    ❌ employment_db 数据库不存在${NC}" | tee -a "$log_file"
            echo "[ERROR] employment_db 数据库不存在" >> "$log_file"
            ((error_count++))
            
            read -p "    是否创建数据库? (y/n): " create_db
            if [ "$create_db" = "y" ] || [ "$create_db" = "Y" ]; then
                if mysql -h "$db_host" -P "$db_port" -u "$db_user" -p"$db_password" -e "CREATE DATABASE employment_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" >/dev/null 2>&1; then
                    echo -e "${GREEN}    ✅ 成功创建 employment_db 数据库${NC}" | tee -a "$log_file"
                    echo "[INFO] 成功创建 employment_db 数据库" >> "$log_file"
                    ((fix_count++))
                else
                    echo -e "${RED}    ❌ 创建数据库失败${NC}" | tee -a "$log_file"
                    echo "[ERROR] 创建数据库失败" >> "$log_file"
                fi
            fi
        fi
    else
        echo -e "${RED}❌ 数据库连接失败${NC}" | tee -a "$log_file"
        echo "[ERROR] 数据库连接失败" >> "$log_file"
        echo "    请检查:"
        echo "    1. MySQL服务是否启动"
        echo "    2. 用户名密码是否正确"
        echo "    3. 防火墙设置"
        ((error_count++))
    fi
else
    echo -e "${YELLOW}⚠️  mysql客户端未安装，无法测试数据库连接${NC}" | tee -a "$log_file"
    echo "[WARN] mysql客户端未安装" >> "$log_file"
fi

echo "" | tee -a "$log_file"
echo "[5/6] 检查JVM和内存设置..." | tee -a "$log_file"

# 检查Java版本
java_version=$(java -version 2>&1 | head -n 1)
echo "    当前Java版本: $java_version" | tee -a "$log_file"

# 检查可用内存
if command -v free >/dev/null 2>&1; then
    total_memory=$(free -m | awk 'NR==2{printf "%.0f", $2}')
    if [ "$total_memory" -lt 2048 ]; then
        echo -e "${YELLOW}⚠️  系统内存较低 (${total_memory} MB)，可能影响应用启动${NC}" | tee -a "$log_file"
        echo "[WARN] 系统内存较低" >> "$log_file"
    else
        echo -e "${GREEN}✅ 系统内存充足 (${total_memory} MB)${NC}" | tee -a "$log_file"
    fi
fi

echo "" | tee -a "$log_file"
echo "[6/6] 生成修复建议..." | tee -a "$log_file"

echo "========================================" | tee -a "$log_file"
echo "            诊断结果报告                " | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "发现问题: $error_count 个" | tee -a "$log_file"
echo "自动修复: $fix_count 个" | tee -a "$log_file"
echo "日志文件: $log_file" | tee -a "$log_file"
echo "========================================" | tee -a "$log_file"
echo "" | tee -a "$log_file"

echo "[$(date)] 诊断完成" >> "$log_file"
echo "[SUMMARY] 发现问题: $error_count, 自动修复: $fix_count" >> "$log_file"

if [ $error_count -gt 0 ]; then
    echo -e "${RED}❌ 发现 $error_count 个问题需要解决${NC}" | tee -a "$log_file"
    echo "" | tee -a "$log_file"
    echo "修复建议:" | tee -a "$log_file"
    echo "1. 检查启动日志中的具体错误信息" | tee -a "$log_file"
    echo "2. 确保所有依赖项版本兼容" | tee -a "$log_file"
    echo "3. 验证数据库连接配置" | tee -a "$log_file"
    echo "4. 检查端口是否被占用" | tee -a "$log_file"
    echo "5. 增加JVM内存设置（如需要）" | tee -a "$log_file"
    echo "" | tee -a "$log_file"
    echo "常用修复命令:" | tee -a "$log_file"
    echo "- 清理重新构建: mvn clean install" | tee -a "$log_file"
    echo "- 刷新依赖: mvn dependency:resolve -U" | tee -a "$log_file"
    echo "- 重启MySQL: sudo systemctl restart mysql" | tee -a "$log_file"
    echo "- 检查端口: lsof -i :8080" | tee -a "$log_file"
    echo "" | tee -a "$log_file"
else
    echo -e "${GREEN}✅ 未发现明显问题，应用应该可以正常启动${NC}" | tee -a "$log_file"
    echo "" | tee -a "$log_file"
    read -p "是否尝试重新启动应用? (y/n): " retry_start
    if [ "$retry_start" = "y" ] || [ "$retry_start" = "Y" ]; then
        echo "正在启动应用..." | tee -a "$log_file"
        cd backend
        mvn spring-boot:run -Dspring-boot.run.profiles=dev
    fi
fi

echo "" | tee -a "$log_file"
echo "如需更详细的诊断信息，请查看日志文件: $log_file" | tee -a "$log_file"